package org.example.exampreparationtreasure.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.exampreparationtreasure.service.QuestionSelectorService;
import org.example.exampreparationtreasure.mapper.QuestionMapper;
import org.example.exampreparationtreasure.model.entity.ExamPaperConfig;
import org.example.exampreparationtreasure.model.entity.Question;
import org.example.exampreparationtreasure.model.entity.PracticeMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 模拟考试题目选择器
 * 模拟真实考试环境，按照考试标准选择题目
 */
@Service
public class MockExamQuestionSelectorServiceImpl implements QuestionSelectorService {

    @Autowired
    private QuestionMapper questionMapper;

    @Override
    public List<Question> selectQuestions(ExamPaperConfig config, Long userId) {
        List<Question> selectedQuestions = new ArrayList<>();

        // 模拟考试的题目分布：简单30%，中等50%，困难20%
        int easyCount = (int) (config.getQuestionCount() * 0.3);
        int mediumCount = (int) (config.getQuestionCount() * 0.5);
        int hardCount = config.getQuestionCount() - easyCount - mediumCount;

        // 选择简单题目
        if (easyCount > 0) {
            selectedQuestions.addAll(getQuestionsByDifficulty("易", easyCount));
        }

        // 选择中等题目
        if (mediumCount > 0) {
            selectedQuestions.addAll(getQuestionsByDifficulty("中", mediumCount));
        }

        // 选择困难题目
        if (hardCount > 0) {
            selectedQuestions.addAll(getQuestionsByDifficulty("难", hardCount));
        }

        // 随机打乱题目顺序，模拟真实考试
        Collections.shuffle(selectedQuestions);

        return selectedQuestions;
    }



    private List<Question> getQuestionsByDifficulty(String difficulty, int count) {
        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("difficulty", difficulty);

        List<Question> allQuestions = questionMapper.selectList(queryWrapper);

        if (allQuestions.size() <= count) {
            return allQuestions;
        }

        Collections.shuffle(allQuestions);
        return allQuestions.subList(0, count);
    }
}
